package org.nimi317.web_gis.aspect;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.nimi317.web_gis.annotation.Division;
import org.nimi317.web_gis.context.SecurityContextHolder;
import org.nimi317.web_gis.data.AreaCodeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author thunderobot
 */
@Component
@Slf4j
public class DivisionAspect {

    @Autowired
    private AreaCodeList areaCodeList;

    @PostConstruct
    public void init() {
        String[] values = SecurityContextHolder.getClassWithDivision();
        Set<Class<?>> beans = new HashSet<>();
        for (String value : values) {
            Set<Class<?>> set = ClassUtil.scanPackage(value, aClass -> ObjectUtil.isNotEmpty(aClass.getAnnotation(Division.class)));
            beans.addAll(set);
        }
        beans.forEach(target -> {
            TableName tableName = target.getAnnotation(TableName.class);
            String name = ObjectUtils.isEmpty(tableName) ? CharSequenceUtil.toUnderlineCase(target.getSimpleName()) : tableName.value();
            log.info("初始化分表策略: {}", name);
            Division division = target.getAnnotation(Division.class);
            areaCodeList.setStrategy(name, division.strategy());
        });
        SecurityContextHolder.remove();
    }
}
